package com.example.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

class MyTask extends RecursiveTask<Integer> {

	private static final long serialVersionUID = 1L;

	private static final Integer VALUE = 10;

	private int begin;
	private int end;
	private int result;

	public MyTask(int begin, int end) {
		this.begin = begin;
		this.end = end;
	}

	@Override
	protected Integer compute() {
		if (end - begin <= VALUE) {
			for (int i = begin; i <= end; i++) {
				result += i;
			}
			return result;
		}

		// 二分法
		int middle = (begin + end) / 2;
		MyTask leftTask = new MyTask(begin, middle);
		MyTask rightTask = new MyTask(middle + 1, end);

		// 调用方法拆分
		leftTask.fork();
		rightTask.fork();
		// 合并结果
		result = leftTask.join() + rightTask.join();
		return result;
	}

}

public class ForkJoinDemo {

	public static void main(String[] args) throws Exception {
		MyTask myTask = new MyTask(0, 100);
		ForkJoinPool forkJoinPool = new ForkJoinPool();
		ForkJoinTask<Integer> forkJoinTask = forkJoinPool.submit(myTask);
		System.out.println(forkJoinTask.get());
		forkJoinPool.shutdown();
	}

}
